// 传入ascii字符串，计算BCC校验和，输出以16进制字符串表示
function chk8xor(strArray) {
	let checksum = 0x00
	for (let i = 0; i < strArray.length; i++) {
		if (strArray.charCodeAt(i) > 255) {
			// 注意汉子GB2132编码，采用先转为字符然后用编码器变为Buffer对象，再遍历异或求解
			// 或者let buffer = Buffer.alloc(3)先分配3个字节，然后用那一堆buf.write...接口求解
			let textEncode = new TextEncoder('gb2132')
			textEncode.encode(String.fromCharCode(strArray.charCodeAt(i))).forEach((item) => {
				checksum ^= item
			})
		} else {
			checksum ^= strArray.charCodeAt(i)
		}
	}
	return checksum.toString(16).toUpperCase().padStart(2, '0')
}
// 传入整个字符串,计算Bcc校验后的字符串
function chk8xorAllStr(wholeStr) {
	const regx = /^\$([0-9a-zA-Z,])*\*/
	let res = wholeStr.match(regx)
	if (res) {
		res = res[0].substring(1, res[0].length - 1)
	} else {
		console.log('正则错误解析!!!')
		return
	}
	return chk8xor(res)
}

const closeDeviceStr =
	'CCICR,1,0'
console.log(chk8xor(closeDeviceStr))
// 构造整个报文函数
module.exports = {
	chk8xor,
	chk8xorAllStr,
}
